﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Web.Security;
using System.Collections;
using NCC_SOP.app_codes;
using System.Data.SqlClient;

namespace NCC_SOP.Admin
{
    public partial class editUser : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                initBind();
                MultiView1.ActiveViewIndex = 0;
            }
        }

        protected void initBind()
        {
            try
            {
                string userName = (string)Session["UserName"];
                if (String.IsNullOrWhiteSpace(userName))
                {
                    Response.Redirect("~/Admin/AdministratorOnly/userManagementPage.aspx", false);
                }
                MembershipUser mu = Membership.GetUser(userName);
                UserNameBox.Text = userName;
                EmailBox.Text = mu.Email;
                ActiveUserList.Items.Add(new ListItem("Active"));
                ActiveUserList.Items.Add(new ListItem("Not Active"));
                if (mu.IsApproved)
                {
                    ActiveUserList.Items.FindByValue("Active").Selected = true;
                }
                else
                {
                    ActiveUserList.Items.FindByValue("Not Active").Selected = true;
                }

                if (mu.LastLockoutDate.Year < 2000) { LastLockoutDate.Text = string.Empty; }
                else { LastLockoutDate.Text = mu.LastLockoutDate.ToShortDateString(); }
                UnlockUserButton.Enabled = mu.IsLockedOut;

                string[] roles = Roles.GetAllRoles();
                PageRoleList.DataSource = roles;
                PageRoleList.DataBind();
                string[] userRoles = Roles.GetRolesForUser(userName);
                foreach (string role in userRoles)
                {
                    foreach (ListItem li in PageRoleList.Items)
                    {
                        if (role.Equals(li.Value))
                        {
                            li.Selected = true;
                        }
                    }
                }

                dbConnection db = new dbConnection();

                ReportRoleList.DataSource = db.getAllRoles();
                ReportRoleList.DataBind();
                string[] reportRoles = db.getReportRolesForUser(userName);
                foreach (string role in reportRoles)
                {
                    foreach (ListItem li in ReportRoleList.Items)
                    {
                        if (role.Equals(li.Value))
                        {
                            li.Selected = true;
                        }
                    }
                }

                DepartmentList.DataSource = db.getAllDepartments();
                DepartmentList.DataBind();
                string[] departments = db.getDepartmentsForUser(userName);
                foreach (string department in departments)
                {
                    foreach (ListItem li in DepartmentList.Items)
                    {
                        if (department.Equals(li.Value))
                        {
                            li.Selected = true;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Session["ErrorMessage"] = e.Message;
                Response.Redirect("~/ErrorDisplayPage.aspx");
            }
        }

        protected void UnlockUserButton_Click(object sender, EventArgs e)
        {
            // Unlock the user account
            try
            {
                string userName = (string)Session["UserName"];
                if (String.IsNullOrWhiteSpace(userName))
                {
                    Response.Redirect("~/Admin/AdministratorOnly/userManagementPage.aspx", false);
                }
                MembershipUser usr = Membership.GetUser(userName);

                usr.UnlockUser();
                UnlockUserButton.Enabled = false;
                //  StatusMessage.Text = "The user account has been unlocked.";
            }
            catch (Exception ee)
            {
                Session["ErrorMessage"] = ee.Message;
                Response.Redirect("~/ErrorDisplayPage.aspx");
            }
        }

        protected void Button1_Click(object sender, EventArgs e)
        {
            cv.Validate();
            try
            {
                if (Page.IsValid)
                {
                    string userName = UserNameBox.Text;
                    string email = EmailBox.Text;

                    // remove old page roles
                    string[] oldRoles = Roles.GetRolesForUser(userName);
                    Roles.RemoveUserFromRoles(userName, oldRoles);

                    // add new page roles
                    string[] rolesToAdd = retrieveFunctions.getSelectedItems(PageRoleList);
                    Roles.AddUserToRoles(userName, rolesToAdd);

                    // find userID from userName
                    MembershipUser user = Membership.GetUser(userName);
                    object userID = user.ProviderUserKey;

                    // remove old page departments
                    for (int i = 0; i < this.DepartmentList.Items.Count; i++)
                    {
                            removeStaffDepartmentMapping(userID, this.DepartmentList.Items[i].Value);
                    }

                    // add new staff departments
                    // find userID from userName
                    for (int i=0; i < this.DepartmentList.Items.Count; i++)
                    {
                        if (this.DepartmentList.Items[i].Selected)
                        {
                            insertStaffDepartmentMapping(userID, this.DepartmentList.Items[i].Value);
                        }
                    }



                    // update email
                    MembershipUser mu = Membership.GetUser(userName);
                    mu.Email = email;

                    // update active/inactive
                    if (ActiveUserList.SelectedValue == "Active")
                    {
                        mu.IsApproved = true;
                    }
                    else
                    {
                        mu.IsApproved = false;
                    }
                    Membership.UpdateUser(mu);

                    dbConnection db = new dbConnection();

                    // remove old report roles
                    string[] oldReportRoles = db.getReportRolesForUser(userName);
                    db.removeUserFromReportRoles(userName, oldReportRoles);

                    // add new report roles
                    string[] reportRolesToAdd = retrieveFunctions.getSelectedItems(ReportRoleList);
                    db.addUserIntoReportRoles(userName, reportRolesToAdd);

                    MultiView1.ActiveViewIndex += 1;
                    EditSuccessLabel.Text = "You have successfully edited the information for \"" + userName + "\".";
                }
            }
            catch (Exception ee)
            {
                Session["ErrorMessage"] = ee.Message;
                Response.Redirect("~/ErrorDisplayPage.aspx");
            }
        }

        private void deleteStaffDepartmentMapping(string userID, string alias)
        {
        }

        private void insertStaffDepartmentMapping(object userID, string alias)
        {
            dbConnection db = new dbConnection();
            string departmentID = db.getDepartmentID(alias);
            using (SqlConnection SqlConnection = new SqlConnection(db.connectionStr))
            {
                
                SqlCommand cmd = new SqlCommand("insert into staffDepartmentMapping(userID, departmentID, createdDt, createdBy, status) values (@userID, @departmentID, @createdDt, @createdBy, @status) ", SqlConnection);
                cmd.Parameters.Add("@userID", SqlDbType.UniqueIdentifier);
                cmd.Parameters.Add("@departmentID", SqlDbType.Int);
                cmd.Parameters.Add("@createdDt", SqlDbType.DateTime);
                cmd.Parameters.Add("@createdBy", SqlDbType.VarChar);
                cmd.Parameters.Add("@status", SqlDbType.VarChar);

                cmd.Parameters["@userID"].Value = userID;
                cmd.Parameters["@departmentID"].Value = departmentID;
                cmd.Parameters["@createdDt"].Value = "2014-01-01";
                cmd.Parameters["@createdBy"].Value = "admin";
                cmd.Parameters["@status"].Value = "active";
                SqlConnection.Open();
                cmd.ExecuteNonQuery();
            }
        }

        private void removeStaffDepartmentMapping(object userID, string alias)
        {
            dbConnection db = new dbConnection();
            string departmentID = db.getDepartmentID(alias);
            using (SqlConnection SqlConnection = new SqlConnection(db.connectionStr))
            {
                SqlCommand cmd = new SqlCommand("delete from staffDepartmentMapping where userID= @userID AND departmentID = @departmentID", SqlConnection);
                cmd.Parameters.Add("@userID", SqlDbType.UniqueIdentifier);
                cmd.Parameters.Add("@departmentID", SqlDbType.Int);

                cmd.Parameters["@userID"].Value = userID;
                cmd.Parameters["@departmentID"].Value = departmentID;
                SqlConnection.Open();
                cmd.ExecuteNonQuery();
            }
        }

        protected void redirectToManageUser(object sender, EventArgs e)
        {
            Session["UserName"] = null;
            Response.Redirect("~/Admin/AdministratorOnly/manageUser.aspx");
        }

        protected void ValidateRole(object source, ServerValidateEventArgs args)
        {
            args.IsValid = false;
            foreach (ListItem li in PageRoleList.Items)
            {
                if (li.Selected)
                {
                    args.IsValid = true;
                }
            }
        }
    }
}